import axios from "axios";
import store from "@/store/index";
import router from "@/router/index";
import { Notify } from "vant";
import * as types from "@/store/mutation-types";

axios.defaults.withCredentials = true;
axios.defaults.timeout = 15000;
axios.defaults.baseURL =
  process.env.NODE_ENV === "production" ? "/api" : "/api";
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded;charset=UTF-8";
/*
 *请求前拦截
 *用于处理需要请求前的操作
 */
axios.interceptors.request.use(
  config => {
    const token = localStorage.getItem("token");
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    store.commit(types.SHOW_LOADING);
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);
/*
 *请求响应拦截
 *用于处理数据返回后的操作
 */
axios.interceptors.response.use(
  response => {
    return new Promise((resolve, reject) => {
      const res = response.data;
      if (res.status === true) {
        res.message &&
          Notify({
            message: res.message,
            duration: 3000,
            background: "#67C23A"
          });
        resolve(res);
      } else {
        res.message && Notify(res.message);
        reject(res);
      }
      store.commit(types.HIDE_LOADING);
    });
  },
  error => {
    console.log(error);
    //请求成功后关闭加载框
    store.commit(types.HIDE_LOADING);
    //断网处理或者请求超时
    if (!error.response) {
      //请求超时
      if (error.message.includes("timeout")) {
        Notify("请求超时,请检查互联网连接后重试");
      }
      return;
    }
    const status = error.response.status;
    switch (status) {
      case 500:
        Notify("服务器错误");
        break;
      case 404:
        Notify("未找到远程服务器");
        break;
      case 401:
        Notify("当前登录已失效，请重新登陆");
        localStorage.removeItem("token");
        router.replace({
          path: "/"
        });
        break;
      case 400:
        Notify("数据异常");
        break;
      default:
        Notify(error.response.data.message);
    }
    return Promise.reject(error);
  }
);

/*
 *get方法，对应get请求
 *@param {String} url [请求的url地址]
 *@param {Object} params [请求时候携带的参数]
 */
export function get(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params
      })
      .then(res => {
        resolve(res);
      })
      .catch(err => {
        reject(err);
      });
  });
}

/*
 *post方法，对应post请求
 *@param {String} url [请求的url地址]
 *@param {Object} params [请求时候携带的参数]
 */
export function post(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, params)
      .then(res => {
        resolve(res);
      })
      .catch(err => {
        reject(err);
      });
  });
}

//上传图片的方法
export function upload(url, data) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, data.formData, {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      })
      .then(res => {
        resolve(res);
      })
      .catch(err => {
        reject(err);
      });
  });
}

/*
 *delete方法，对应delete请求
 *@param {String} url [请求的url地址]
 *@param {Object} params [请求时候携带的参数]
 */
export function deletes(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .delete(url, params)
      .then(res => {
        resolve(res);
      })
      .catch(err => {
        reject(err);
      });
  });
}
